$(function () {
    let interval = setInterval(() => {
        window.location.reload()
    }, 200);
    clearInterval(interval);
    $(window).on("load", () => {
        class GoodList {
            constructor() {
                this.init();
                
            }
            init() {
                this.goodslist = $(".goods-list");
                this.data = null;

                this.getData();

                //分页器
                this.page_no = 1;

                // 获取cookie数据ID,TOKEN
                this.ID = cookie("ID");
                this.TOKEN = cookie("TOKEN");

                if(this.ID.length > 0 && this.TOKEN.length > 0){
                    $("#userDropdown").css("display","flex");
                    // 存在免登录信息
                    this.getUserInfo();
                }else{
                    $("#loginBtn").css("display","flex");
                    
                }
            }
            
            getUserInfo() {
                var _this = this;
                $.ajax({
                    url: "http://localhost:8888/users/info/" + this.ID,
                    headers: {
                        "authorization": this.TOKEN
                    },
                    dataType: "json",
                    
                }).then(function(res){
                    _this.nickname.html(res.info.nickname);
                })
                
            }
            
            getData() {
                var _this = this;
                $.getJSON("../static/data/diamonds.json", function (json) {
                    let data = json.data;
                    // console.log(data);
                    _this.render(data);

                    _this.bindEvent(data);

                    _this.initPagination(data)

                    //     localStorage.setItem("shuju",JSON.stringify(data))
                    //    localStorage.getItem("shuju")
                });
            }


            bindEvent(data) {
                // console.log(this);
                var _this = this;
                // console.log(_this);
                this.goodslist = $(".goods-list");
                this.goods_item = $(".goods-item")
                this.goods_pic = $(".img_main")
                this.hsort = $(".ab")
                this.dsort = $(".ac")


                 //跳转详情
                 $(".goods-list").click((e)=>{
                    _this.go( $(e.target).attr("data-id" ));
                 })
                //  this.goodslist.on("click" , ".goods-item" ,(e)=>{
                    // _this.go( $(e.target).attr("data-id" ));
                    // console.log($(e.target).attr("data-id" ));
                //  })
                 
                
                   

                //up
                this.hsort.click(function () {
                    _this.sortHandleup(data);
                    // console.log(data[1].price);
                })
                //down
                this.dsort.click(function () {
                    _this.sortHandledown(data);
                })

                for (let i = 0; i < this.goods_item.length; i++) {
                    this.goods_pic.eq(i).mouseover(function () {
                        _this.goods_pic.eq(i).attr("data-src", data[i].img_sec)

                    })
                }
               
            }

            go(id){
                location.href = "./goodsdet.html#id=" + id
            }
            //排序
            //up
            sortHandleup(data) {
                for (let i = 0; i < data.length; i++) {
                    for (let k = 0; k < data.length - 1 - i; k++) {
                        if (
                            data[k].price.slice(1) - 0 >
                            data[k + 1].price.slice(1) - 0
                        ) {
                            let temp = data[k];
                            data[k] = data[k + 1];
                            data[k + 1] = temp;
                        }
                    }
                }
                new Pagination(data, {
                    pagination: ".pagination",
                    callback: function () {
                        this.render();
                        new LazyLoad(".imgBox .img_main");
                    },
                });
            }
            //down
            sortHandledown(data) {
                for (let i = 0; i < data.length; i++) {
                    for (let k = 0; k < data.length - 1 - i; k++) {
                        if (
                            data[k].price.slice(1) - 0 <
                            data[k + 1].price.slice(1) - 0
                        ) {
                            let temp = data[k];
                            data[k] = data[k + 1];
                            data[k + 1] = temp;
                        }
                    }
                }

                new Pagination(data, {
                    pagination: ".pagination",
                    callback: function () {
                        this.render();
                        new LazyLoad(".imgBox .img_main");
                    },
                });

               
            }




            // 数据渲染

            render(data) {
               
                this.goodslist.html($.map(data,
                    (item) => `
                    <li class="goods-item" data-id=${item.id}>
                        <div class="zong" data-id=${item.id}>
                            <div class="imgBox" data-id=${item.id}>
                                <div class="tubia icon-theheart">
                                </div>
                                <img src="${item.img}" style="width:100%;" class="img_main" data-id=${item.id}>
                                <img src="${item.img_hover}" style="width:100%;" class="img_sec" data-id=${item.id}>
                                
                            </div>
                            <div class="dring_thing-cort" data-id=${item.id}>
                                <p class="dring_thing-word" data-id=${item.id}>
                                    ${item.name}
                                </p>
                                <div class="dring_thing-button" data-id=${item.id}>
                                    <span class="dring_thing-price" data-id=${item.id}>
                                        ${item.price}
                                    </span>
                                    
                                    <div class="submitBtn buy-btn" data-id=${item.id} >
                                        <span  data-id=${item.id}>立即购买</span>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    </li>
                    `

                ).join(""))

                // $(".imgBox").hover((e) => {
                   
                //     $(e.target).css({
                //             display: "none"
                //         }),

                //         $(e.target).siblings().css({
                //             display: "inline-block"
                //         })
                // })


                // $(".imgBox").mouseout((e) => {
                //     // console.log($(e.target));
                //     $(e.target).css({
                //             display: "inline-block"
                //         }),

                //         $(e.target).siblings().css({
                //             display: "none"
                //         })
                // })


                // $(".buy-btn").hover((e)=>{
                //     $(e.target).css({
                //         display : "inline-block"
                //     })
                // })

                // $(".buy-btn").click(function () {
                //     location.href = "./index.html"
                // })

             }

            //分页器
           
            initPagination(data) {
                new Pagination(data, {
                    Pagination: ".pagination",
                    callback: function () {
                        //渲染每页数据
                        // let arr = [];
                        // for (var i = 0; i < this.show_num; i++) {
                        //     arr.push(this.data[this.index * this.show_num + i]);
                        // }
                        this.render();

                        new LazyLoad(".imgBox .img_main");
                    }
                })
            }



        }
        new GoodList();


        class Pagination {
            constructor(data, options) {
                // 创建默认参数; 
                Object.assign(this, {
                        // 一页默认显示数据; 
                        show_num: 9,
                        // 当前的页码 ; 
                        index: 0,
                        // 分页内容总条数; 
                        count: data.length,
                        // 中间显示的页码数量; 
                        show_page_count: 5,
                        pagination: "",
                        callback: function () {}
                    },
                    options)

                this.data = data;
                this.container = $(".goods-list");
                this.pagination = $(".pagination")
                //计算总页数
                this.total_page_num = Math.ceil(this.count / this.show_num);
                // show_page_count 数据必须是奇数;
                if (this.show_page_count % 2 !== 1) {
                    this.show_page_count++;
                }

                this.render();
                // new LazyLoad(".imgBox .img_main");
                this.renderBullet();
                this.bindEvent();

                
            };
            bindEvent() {
                this.pagination.on("click", "span", (e) => {
                    this.index = $(e.target).text() - 1;
                    this.render();
                    this.renderBullet();
                })
                this.pagination.on("click", ".start", (e) => {
                    this.index = 0;
                    this.render();
                    this.renderBullet();
                })
                this.pagination.on("click", ".end", (e) => {
                    this.index = this.total_page_num - 1;
                    this.render();
                    this.renderBullet();
                })
                this.pagination.on("click", ".next", (e) => {
                    this.add();
                })
                this.pagination.on("click", ".prev", (e) => {
                    this.reduce();
                })
                this.pagination.on("click", "selectstart", (e) => {
                    e.preventDefault();
                })
            }
            render() {
                let html = "";
                for (let i = this.index * this.show_num; i < (this.index + 1) * this.show_num; i++) {
                    if (this.data[i] === undefined) continue;


                    html += ` <li class="goods-item" data-id=${this.data[i].id}>
                    <div class="zong" data-id=${this.data[i].id}>
                        <div class="imgBox" data-id=${this.data[i].id}>
                        <div class="tubia icon-theheart"></div>
                            <img data-id=${this.data[i].id} src="../static/images/loading.gif" data-src="${this.data[i].img}" style="width:100%;" class="img_main"  >
                            <img data-id=${this.data[i].id} src="${this.data[i].img_hover}" style="width:100%;" class="img_sec">
                            
                        </div>
                        <div class="dring_thing-cort" data-id=${this.data[i].id}>
                            <p class="dring_thing-word" data-id=${this.data[i].id}>
                                ${this.data[i].name}
                            </p>
                            <div class="dring_thing-button" data-id=${this.data[i].id}>
                                <span class="dring_thing-price" data-id=${this.data[i].id}>
                                    ${this.data[i].price}
                                </span>
                                
                                <div class="submitBtn buy-btn" data-id=${this.data[i].id}>
                                    <span data-id=${this.data[i].id}>立即购买</span>
                                </div>
                            </div>
                        </div>
                        
                    </div>
                </li>`
                }
                this.container.html(html);

                // $(".imgBox").hover((e) => {
                   
                //     $(e.target).css({
                //             display: "none"
                //         }),

                //         $(e.target).siblings().css({
                //             display: "inline-block"
                //         })
                // })


                // $(".imgBox").mouseout((e) => {
                //     // console.log($(e.target));
                //     $(e.target).css({
                //             display: "inline-block"
                //         }),

                //         $(e.target).siblings().css({
                //             display: "none"
                //         })
                // })
                // $(".buy-btn").click(function () {
                //     location.href = "./index.html"
                // })
            }

            renderBullet() {
                //创建结构的核心在于，当前页面有多少条数据;
                // - 总页数计算方式 : 总数量 / 每页显示数量 向上取整
                let html = "";
                html += "<em class='prev'>上一页</em>";
                html += "<strong class='start'>开头</strong>";

                let start = this.index - 1;
                let end = this.index + 3;

                // - 判定分页的起始点;
                if (this.index <= 2) {
                    start = 1;
                    end = start + this.show_page_count;
                }

                if (
                    this.total_page_num > this.show_page_count + 1 &&
                    this.index >= this.total_page_num - 2
                ) {
                    end = this.total_page_num;
                    start = end - 5;
                }

                if (end >= this.total_page_num) {
                    end = this.total_page_num;
                }
                if (!(this.total_page_num > this.show_page_count + 1)) {
                    start = 1;
                }

                if (this.total_page_num > this.show_page_count + 1 && this.index >= 3) {
                    html += "<span>1</span>";
                    html += "<b>...</b>";
                }

                // 带有省略号的渲染;
                for (let i = start; i <= end; i++) {
                    html += `<span ${
                    i - 1 === this.index ? "class='active'" : ""
                  }>${i}</span>`;
                }

                if (
                    this.total_page_num > this.show_page_count + 1 &&
                    this.index <= this.total_page_num - 4
                ) {
                    html += "<b>...</b>";
                    html += "<span>" + this.total_page_num + "</span>";
                }

                html += "<strong class='end'>结尾</strong>";
                html += "<em class='next'>下一页</em>";

                this.pagination.html(html);
                this.callback();
            }
            add() {
                if (this.index >= this.total_page_num - 1) {
                    return false;
                }
                this.index++;
                this.render();
                this.renderBullet();
            }
            reduce() {
                if (this.index <= 0) {
                    return false;
                }
                this.index--;
                this.render();
                this.renderBullet();
            }
        }



    })
})